package com.smartstate.EnvironmentMonitor.websocket;


import com.smartstate.EnvironmentMonitor.config.BeanContext;
import com.smartstate.EnvironmentMonitor.entity.Systemmonitor;
import com.smartstate.EnvironmentMonitor.mapper.HistoryMapper;
import com.smartstate.EnvironmentMonitor.schedul.DataRealThread;
import com.smartstate.EnvironmentMonitor.service.SystemmonitorService;
import com.smartstate.EnvironmentMonitor.vo.DataVO;
import com.smartstate.EnvironmentMonitor.vo.ResultVO;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

@Slf4j
public class DataRealTimeRunnable implements Runnable{

    private Map<String, List<DataVO>> mapAttribute = new HashMap<>();

    private HistoryMapper historyMapper;

    private SystemmonitorService systemmonitorService;

    private List<DataVO> dataVOList;

    private String userId;

    private  String check;

    ExecutorService executorService = Executors.newFixedThreadPool(10);

    DataRealTimeRunnable(){
        historyMapper = BeanContext.getApplicationContext().getBean(HistoryMapper.class);
        systemmonitorService = BeanContext.getApplicationContext().getBean(SystemmonitorService.class);
    }

    public void setListAndUserId(List<DataVO> dataVOList, String userId){
        this.dataVOList = dataVOList;
        this.userId = userId;
        this.check = userId;
    }

    @SneakyThrows
    @Override
    public void run() {
        if(dataVOList != null && dataVOList.size() > 0){
            long startTime = System.currentTimeMillis();
            List<Future> futureList = new ArrayList<>();
            dataVOList.forEach((dataVO) ->{
                futureList.add(executorService.submit(new DataRealThread(userId, dataVO, check)));
            });
            for (Future future : futureList) {
                Map<String, List<DataVO>> listMap = (Map<String, List<DataVO>>) future.get();
                mapAttribute.putAll(listMap);
            }
            WebSocket.send(ResultVO.ok(mapAttribute,"realTimeProperties"), userId);
            check = "";
            long endTime = System.currentTimeMillis();
            log.info("读取时间：： "+(endTime - startTime));
        }else {
//            发送系统监控数据
            List<Systemmonitor> boxStatus = systemmonitorService.getDeviceStatus();
            WebSocket.send(ResultVO.ok(boxStatus, "boxStatus"), userId);
        }

    }



}
